import { Component, OnInit } from '@angular/core'
import { Router } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { ThrowStmt } from '@angular/compiler'

declare var $: any
@Component({
  selector: 'sa-firmware-page',
  templateUrl: './firmware-page.component.html'
})
export class FirmwarePageComponent implements OnInit {
  validatorOptions = {
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {}
  }
  binNameList: any = [] //用户数据List
  page: any = {
    companyId: '',
    companyName: '',
    useTypeL1: '',
    useTypeL2: '',
    hwVersion: '',
    sensorNum: '-1',
    binName: '',
    version: '',
    packetTotal: '',
    binSize: '',
    binId: '',
    description: '',
    protocolVersion: ''
  }
  page_title: string = '添加'
  pageType: string = 'new'
  carTypeList = carTypeListObj.carTypeList
  constructor(private router: Router, private jsonApiService: JsonApiService) { }
  //上传提交
  uploadFile() {
    this.page.useTypeL2 = $('#useTypeSelect').val()
    this.page.useTypeL1 = $('#useTypeSelect').val().slice(0, 2)
    let postParam = new FormData()

    if (!this.page.companyId) {
      this.jsonApiService.message('请选择所属公司')
      return
    }

    if (!this.page.useTypeL1) {
      this.jsonApiService.message('请选择车辆用途')
      return
    }

    if (!this.page.hwVersion) {
      this.jsonApiService.message('请选择硬件版本')
      return
    }

    if (!this.page.binId) {
      this.jsonApiService.message('请选择固件名称')
      return
    }
    for (let item in this.page) {
      postParam.append(item, this.page[item])
    }
    this.jsonApiService.form_http('bininfoForOM/addBininfoLink.html', postParam).subscribe(data => {
      this.jsonApiService.message(data.message)
      this.goBack()
    })
  }
  //删除选中值
  delbinName() {
    this.page.binName = ''
    this.page.binNameId = ''
    $('#userNameSelect2').val('')
  }
  onSubmit(e) { }
  //返回列表页
  goBack() {
    this.router.navigate(['/system-config/firmware-operation'])
  }
  ngOnInit() {
    const that = this
    this.initAllBinName().then(() => {
      this.selectBinName()
    })
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#useTypeSelect').select2({ language: 'zh-CN' }).on('select2:select', function (e) {
          // 查找默认固件
          that.findDefaultBinInfo()
        })
      })
    })

  }

  versionChange(e) {
    this.findDefaultBinInfo()
  }


  // 根据 车辆用途、硬件版本 关联获取默认固件
  findDefaultBinInfo() {
    const that = this
    const useTypeL2 = $('#useTypeSelect').val()
    const hwVersion = this.page.hwVersion


    if (!useTypeL2 || !hwVersion) return

    let reqData = 'useTypeL2=' + useTypeL2 + '&hwVersion=' + hwVersion;
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('bininfo/findDefaultBinInfo.html', reqData).subscribe(data => {
        if (data.success) {

          if (data.message === '无默认固件') {
            // 清空选中
            $('#binNameSelect2').val('');
            $('#binNameSelect2').trigger('change');
            // https://select2.org/programmatic-control/add-select-clear-items
            // 触发 select2 事件
            $('#binNameSelect2').trigger({
              type: 'select2:select',
              params: {
                data: {
                  id: '',
                  text: '',
                  version: '',
                  packetTotal: '',
                  binSize: '',
                  description: '',
                  protocolVersion: ''
                }
              }
            });
            return
          }
          const binName = data.data.id

          const info = data.data

          $('#binNameSelect2').val(binName);
          $('#binNameSelect2').trigger('change');
          // https://select2.org/programmatic-control/add-select-clear-items
          // 触发 select2 事件
          $('#binNameSelect2').trigger({
            type: 'select2:select',
            params: {
              data: {
                id: info.id,
                text: info.binName,
                version: info.version,
                packetTotal: info.packetTotal,
                binSize: info.binSize,
                description: info.description,
                protocolVersion: info.protocolVersion
              }
            }
          });
        }
        resolve(null)
      })
    })
  }
  selectBinName() {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#binNameSelect2')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: that.binNameList //为Select添加数据
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.page.binName = data.text
            that.page.binId = data.id
            that.page.version = data.version
            that.page.packetTotal = data.packetTotal
            that.page.binSize = data.binSize
            that.page.description = data.description
            that.page.protocolVersion = data.protocolVersion
          })
      })
    })
  }
  initAllBinName() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('bininfo/bininfoListByBinName.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              text: userList[i].binName,
              version: userList[i].version,
              packetTotal: userList[i].packetTotal,
              binSize: userList[i].binSize,
              description: userList[i].description,
              protocolVersion: userList[i].protocolVersion
            }
            selectdata[i] = obj
          }
        }
        that.binNameList = selectdata
        resolve()
      })
    })
  }
  //公司选中回调
  companySelected(data) {
    this.page.companyId = data.companyId
    this.page.companyName = data.companyName
  }
}
